<template>
    <div class="crm-project-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:mysel:project:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.projectName" placeholder="请输入项目名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.customerName" placeholder="请输入客户/企业名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入合同名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.projectStatus" placeholder="请选择状态" multiple clearable class="w100">
                        <el-option label="未开始" value="0"></el-option>
                        <el-option label="进行中" value="1"></el-option>
                        <el-option label="已完成" value="2"></el-option>
                        <el-option label="已暂停" value="3"></el-option>
                        <el-option label="已终止" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="完成时间" value="finishTime"></el-option>
                        <el-option label="开始时间" value="projectStartTime"></el-option>
                        <el-option label="结束时间" value="projectEndTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-table ref="tableCrmProjectRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="center" width="50" show-overflow-tooltip>
                    <template #header>
                        <!-- 使用 el-popover 包裹 el-checkbox-group -->
                        <el-popover placement="bottom-start" :width="100" trigger="click">
                            <template #reference>
                                <!-- 点击触发器：这里放置图标 -->
                                <svg-icon name="el-icon-setting" style="cursor: pointer;"></svg-icon>
                            </template>
                            <!-- el-checkbox-group 放置在此处 -->
                            <el-checkbox-group v-model="tableData.header.selections">
                                <el-checkbox v-for="item in tableData.header.data" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column type="expand" align="cneter" width="50" show-overflow-tooltip>
                    <template #default="scope">
                        <MyselProjectProcess :project="scope.row"></MyselProjectProcess>
                    </template>
                </el-table-column>
                <el-table-column label="项目名称" prop="projectName" v-if="tableData.header.selections.includes('projectName')" min-width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户/企业" prop="customerName" v-if="tableData.header.selections.includes('customerName')" min-width="200" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.customerName && scope.row.enterpriseName">{{scope.row.enterpriseName}}</span>
                        <span v-if="scope.row.customerName == undefined">{{ scope.row.enterpriseName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合同编号" prop="contractCode" v-if="tableData.header.selections.includes('contractCode')" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同名称" prop="contractName" v-if="tableData.header.selections.includes('contractName')" width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="提成金额" prop="quotaAmount" v-if="tableData.header.selections.includes('quotaAmount')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.quotaAmount}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="项目状态" prop="projectStatus" v-if="tableData.header.selections.includes('projectStatus')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.projectStatus == '0'" class="color-info">未开始</span>
                        <span v-else-if="scope.row.projectStatus == '1'" class="color-primary">进行中</span>
                        <span v-else-if="scope.row.projectStatus == '2'" class="color-success">已完成</span>
                        <span v-else class="color-warning">已暂停</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" prop="projectStartTime" v-if="tableData.header.selections.includes('projectStartTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="结束时间" prop="projectEndTime" v-if="tableData.header.selections.includes('projectEndTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="完成时间" prop="finishTime" v-if="tableData.header.selections.includes('finishTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" v-if="tableData.header.selections.includes('createTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="200" v-auths="['crm:project:info', 'crm:project:activing', 'crm:project:paused', 'crm:project:finished']">
                    <template #default="scope">
                        <el-button v-auth="'crm:project:info'" type="primary" link @click="onOpenInfoCrmProject(scope.row)">详情</el-button>
                        <el-button v-auth="'crm:project:activing'" v-show="['0','3'].includes(scope.row.projectStatus)" type="primary" link @click="onOpenCrmProjectStatus(scope.row, '1')">启动</el-button>
                        <el-button v-auth="'crm:project:paused'" v-show="['1'].includes(scope.row.projectStatus)" type="primary" link @click="onOpenCrmProjectStatus(scope.row, '3')">暂停</el-button>
                        <el-button v-auth="'crm:project:finished'" v-show="['1','3'].includes(scope.row.projectStatus)" type="primary" link @click="onOpenCrmProjectStatus(scope.row, '2')">完成</el-button>
                        <el-button v-auth="'crm:project:activing'" v-show="['2'].includes(scope.row.projectStatus)" type="primary" link @click="onOpenCrmProjectStatus(scope.row, '1')">重启</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <InfoCrmProject ref="infoCrmProjectRef"></InfoCrmProject>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import InfoCrmProject from '/@/views/crm/project/infoCrmProject.vue';
import MyselProjectProcess from '/@/views/crm/mysel/project/process/index.vue';
import { editCrmProjectStatus } from '/@/api/crm/project/index';
import { getMyselProjectList } from '/@/api/crm/mysel/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/mysel/project',
    components: { InfoCrmProject, MyselProjectProcess },
    setup() {
        const tableCrmProjectRef = ref();
        const infoCrmProjectRef = ref();
        const state = reactive({
            search:{
                contractCode: undefined,
                contractName: undefined,
                projectName: undefined,
                customerName: undefined,
                projectStatus: [],
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false,
                header: {
                    selections: ['contractCode', 'contractName', 'projectName', 'customerName', 'quotaAmount', 'projectStatus', 'projectStartTime', 'projectEndTime', 'finishTime', 'createTime'],
                    data: [
                        { label: '合同编号', value: 'contractCode' },
                        { label: '合同名称', value: 'contractName' },
                        { label: '项目名称', value: 'projectName' },
                        { label: '客户/企业', value: 'customerName' },
                        { label: '提成金额', value: 'quotaAmount' },
                        { label: '项目状态', value: 'projectStatus' },
                        { label: '开始时间', value: 'projectStartTime' },
                        { label: '结束时间', value: 'projectEndTime' },
                        { label: '完成时间', value: 'finishTime' },
                        { label: '创建时间', value: 'createTime' },
                    ],
                },
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const projectStatusStr = search.projectStatus.join(',');
            getMyselProjectList({
                ...search,
                projectStatus: projectStatusStr
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmProjectRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.projectName = undefined;
            state.search.customerName = undefined;
            state.search.projectStatus = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };

        const onOpenInfoCrmProject = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmProjectRef.value.openDialog(row);
        };

        const projectStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '启动',
                '2': '完成',
                '3': '暂停',
            };
            return statusMap[status] || '未知';
        };

        const onOpenCrmProjectStatus = (row: object, status: string) => {
            ElMessageBox.confirm(`确认【${ projectStatusText(status) }】操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                editCrmProjectStatus({ id: row.id, status: status }).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        // 页面加载时
        onMounted(() => {
            const selections = Local.get('mysel_crm_project_header_selections');
            if(selections){
                state.tableData.selections = selections;
            }
            loadTableData({});
        });

        watch(() => state.tableData.header.selections, (selections) => {
            nextTick(() => {
                Local.set('mysel_crm_project_header_selections', selections)
                tableCrmProjectRef.value.doLayout();
            });
        }, { deep: true });

        return {
            tableCrmProjectRef,
            infoCrmProjectRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenInfoCrmProject,
            onOpenCrmProjectStatus,
            ...toRefs(state),
        };
    },
};
</script>